package thinkinginjava.container;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class ListDemo {
	private static final int SIZE = 1000000;
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		System.out.println(SIZE);
		
//		consumeTimeWhenAdd(LinkedList.class);
//		consumeTimeWhenAdd(ArrayList.class);
		consumeTimeWhenInsert(LinkedList.class);
//		consumeTimeWhenInsert(ArrayList.class);
		
		consumeTimeWhenGet(LinkedList.class);
//		consumeTimeWhenGet(ArrayList.class);
	}
	
	public static void consumeTimeWhenAdd(Class<? extends List> c ) throws InstantiationException, IllegalAccessException {
		List list = c.newInstance();
		long s;
		s = System.currentTimeMillis();
		for(int i = 0; i < SIZE; i ++) {
			list.add(i);
			
		}
		System.out.println("Class: " + c.getName() + " consumes: " + (System.currentTimeMillis() - s) + " ms");
	}
	
	private static Random ra = new Random(47);
	public static void consumeTimeWhenInsert(Class<? extends List> c ) throws InstantiationException, IllegalAccessException {
		List list = c.newInstance();
		for(int i = 0; i < SIZE; i ++) {
			list.add(i);
		}
		long s;
		s = System.currentTimeMillis();
		for(int i = 0; i < 10000; i ++) {
			list.add(SIZE / 2, i); 
		}
		System.out.println("Class: " + c.getName() + " consumes: " + (System.currentTimeMillis() - s) + " ms");
	}
	
	public static void consumeTimeWhenGet(Class<? extends List> c ) throws InstantiationException, IllegalAccessException {
		List list = c.newInstance();
		for(int i = 0; i < SIZE; i ++) {
			list.add(i);
		}
		long s;
		s = System.currentTimeMillis();
		for(int i = 0; i < 10000; i ++) {
			list.get(SIZE / 2);
		}
		System.out.println("Class: " + c.getName() + " consumes: " + (System.currentTimeMillis() - s) + " ms");
	}
}
